<template>
  <header class="parallax-header">
    <div class="parallax-bg" :style="parallaxStyle"></div>
    <div class="content">
      <slot name="content">
        <!-- Default content if no slot is provided -->
        <h1>{{ title }}</h1>
        <p>{{ subtitle }}</p>
      </slot>
    </div>
  </header>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue';

interface Props {
  title?: string;
  subtitle?: string;
  backgroundImage: string;
  speedFactor?: number;
}

const props = withDefaults(defineProps<Props>(), {
  title: '视差头部',
  subtitle: '这是一个具有视差效果的头部组件',
  speedFactor: 0.5,
});

const scrollY = ref(0);

const handleScroll = () => {
  scrollY.value = window.scrollY;
};

const parallaxStyle = computed(() => ({
  backgroundImage: `url(${props.backgroundImage})`,
  transform: `translateY(${scrollY.value * props.speedFactor}px)`,
}));

onMounted(() => {
  window.addEventListener('scroll', handleScroll);
});

onUnmounted(() => {
  window.removeEventListener('scroll', handleScroll);
});
</script>

<style scoped>
.parallax-header {
  position: relative;
  height: 60vh; /* Adjust height as needed */
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: center;
  text-align: center;
  color: white;
}

.parallax-bg {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 150%; /* Increased height to allow for parallax movement */
  background-size: cover;
  background-position: center;
  will-change: transform; /* Optimize for transform animations */
  z-index: -1;
}

.content {
  position: relative;
  z-index: 1;
  padding: 20px;
  background-color: rgba(0, 0, 0, 0.3); /* Optional: adds a slight overlay for better text readability */
  border-radius: 8px;
}

.content h1 {
  font-size: 3rem;
  margin-bottom: 0.5rem;
  font-weight: bold;
  text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.5);
}

.content p {
  font-size: 1.5rem;
  text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.5);
}
</style>